package study_2;

import utils.Tools;

/**
 * 竞态
 * 描述：多线程编程中经常遇到一个问题就是对于同样的输入，程序的输出有时候是正确的而有的时候却是错误的。这种一个计算结果的正确性与时间有关的现象就被称为竞态
 */
public class Thread_2_1 {

    public static void main(String[] args) throws Exception{
        //客户端线程数
        int numberOfThreads = args.length > 0 ? Short.valueOf(args[0]) : Runtime.getRuntime().availableProcessors();
        Thread[] workerThreads = new Thread[numberOfThreads];
        for (int i = 0; i < numberOfThreads; i++) {
            workerThreads[i] = new WorkerThread(i, 100);
        }
        for (Thread ct :
                workerThreads) {
            ct.start();
        }
    }

    //模拟业务线程
    static class WorkerThread extends Thread{
        private final int requestCount;

        public WorkerThread(int id, int requestCount){
            super("worker-" + id);
            this.requestCount = requestCount;
        }

        @Override
        public void run(){
            int i = requestCount;
            String requestID;
            RequestIdGenerator requestIdGen = RequestIdGenerator.getInstance();
            while(i-->0){
                //生成Request ID
                requestID = requestIdGen.nextID();
                processRequest(requestID);
            }
        }

        //模拟请求处理
        private void processRequest(String requestID){
            //模拟请求处理耗时
            Tools.randomPause(50);
            System.out.printf("%s got requestID: %s %n", Thread.currentThread().getName(), requestID);
        }
    }
}
